package com.myebills.ebpsfrontend.cust.controller;

/* LUE ADD */
import java.text.*;
import java.util.Calendar;
import java.util.*;
import java.util.Date;
import java.sql.*;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.checkfree.isolutions.property.Properties;
import com.checkfree.isolutions.property.PropertiesConfig;

/* END LUE ADD */

/**
 * Module Name  : EbppxUtil
 * Description  : Useful utilities.
 * Last Updated : 2002-09-30
 *
 * @author
 *
 * Remarks : 1) 2002-09-25 Lue Added getCurrentTimestamp()
 *           2) 2002-09-25 Lue Changed nullToEmpty()
 *           3) 2002-09-30 Lue Added emptyToDefault()
 *           4) 2002-10-21 Lendy Added getVersion()
 *
 */

public class EbppxUtil {

	public static ArrayList paginate(ArrayList objList,int pageNo) {
		int maxPerPage = 6;
		ArrayList paginatedList = new ArrayList();
		try{
			if(maxPerPage*pageNo<objList.size()){
				for (int index = maxPerPage*(pageNo-1); index < pageNo*maxPerPage; index++) {
					paginatedList.add(objList.get(index));
				}
			}else{
				for (int index = maxPerPage*(pageNo-1); index < objList.size(); index++) {
					paginatedList.add(objList.get(index));
				}
			}
		}catch (Exception e1) {
			System.out.println("Exception: " + e1.toString());
		}catch (Throwable e2) {
			System.out.println("Export error: " + e2.toString());
		}
		return paginatedList;
	}

	public static int getNoOfPages(int listSize) {
		int maxPerPage = 6;
		int NumPages = listSize/maxPerPage;
		try{
			if ((listSize%maxPerPage) > 0){
				NumPages++;
			}
		}catch (Exception e1) {
			System.out.println("Exception: " + e1.toString());
		}catch (Throwable e2) {
			System.out.println("Export error: " + e2.toString());
		}
		return NumPages;
	}


    /**
     * Return <b>true</b> iff s is one of "true", "yes", or "on" (case insensitive).
     * If s is null, return false.
     */
    public static final boolean boolFromString(String s) {
        return boolFromString(s, false);
    }
    /**
     * Return <b>true</b> iff s is one of "true", "yes", or "on" (case insensitive).
     * If s is null, return bDefault.
     */
    public static final boolean boolFromString(String s, boolean bDefault) {
        return (null == s) ? bDefault
        : s.equalsIgnoreCase("true")
        || s.equalsIgnoreCase("yes")
        || s.equalsIgnoreCase("on");
    }

    /**
     * If s is null, or "null", return "".
     * Otherwise, return s.
     * This is useful in JSP's, where getParameter() will return "null" if s is not defined in request.
     */
    public static String nullToEmpty(String s) {
        return (null == s || s.equalsIgnoreCase("null")) ? "" : s.trim(); //LUE CHANGED. ADDED TRIM
    }

    /**
     * If s is null, or "null", or "", return default value.
     * Otherwise, return s.
     * This is useful in JSP's, where getParameter() will return "null" if s is not defined in request.
     */
    public static String emptyToDefault(String s, String strDefault) {
        return (null == s || s.trim().equalsIgnoreCase("null") || s.trim().equals("") ) ? strDefault : s.trim();
    }


    /**
     * Encode a data insertion value to prevent any interpretation by the
     * browser as HTML characters.
     * (This is equivalent to the <b>Server.HtmlEncode</b> function in
     * Microsoft Active Server Pages.)
     * <p>
     * Perform the following conversions:
     * <ul>
     * <li>ampersand (&amp;) to <b>&amp;amp;</b>
     * <li>quotation (&quot;) to <b>&amp;quot;</b>
     * <li>apostrophe (&#39;) to <b>&amp;#39;</b>
     * <li>angle brackets (&lt; &gt;) to <b>&amp;lt;</b> and <b>&amp;gt;</b>
     * </ul>
     *
     * @param   s the input data text (null is treated as an empty string).
     *
     * @return  the encoded data text.
     */
    public static String htmlEncode(String s) {
        // Be sure to replace any ampersands FIRST,
        // to avoid replacing the ones that encode other characters.
        String encoded = replaceText(s, "&", "&amp;");

        encoded = replaceText(encoded, "\"", "&quot;");
        encoded = replaceText(encoded, "'", "&#39;");
        encoded = replaceText(encoded, "<", "&lt;");
        encoded = replaceText(encoded, ">", "&gt;");

        return encoded;
    }

    /**
     * Replace all occurrences of a given search string with a replacement
     * string.
     *
     * @param   inputString the text which needs to be corrected.
     *          A null value is treated as an empty String ("").
     *
     * @param   searchText the text to be replaced by
     *          <code>replacementText</code>.
     *          A null or empty value is ignored.
     *
     * @param   replacementText the new text that will replace
     *          <code>searchText</code>.
     *          A null value is treated as an empty String ("").
     *
     * @return  the corrected text.
     */
    public static String replaceText(
    String inputString,
    String searchText,
    String replacementText
    ) {
        String s = inputString;
        if (s == null) {
            s = "";
        }

        if ((searchText != null) && (searchText.length() > 0)) {
            if (replacementText == null) {
                replacementText = "";
            }
            int replacementLength = replacementText.length();

            int searchLength = searchText.length();

            // Postpone allocation of any new objects until we are sure
            // we have something to change.
            StringBuffer corrected = null;

            int startLoc = 0;
            int loc = s.indexOf(searchText, startLoc);
            while (loc >= 0) {
                if (corrected == null) {
                    // Guarantee at least enough capacity for the original text
                    // plus the first replacement text.
                    // We ignore the first removal of the search text,
                    // since we can allocate a little extra space without harm.
                    corrected = new StringBuffer(s.length() + replacementLength);
                }
                corrected.append(s.substring(startLoc, loc));
                corrected.append(replacementText);
                startLoc = loc + searchLength;
                loc = s.indexOf(searchText, startLoc);
            }
            if (corrected != null) {
                // Only allocate a new String object if we actually made
                // some changes to the original copy.
                corrected.append(s.substring(startLoc));
                s = corrected.toString();
            }
        }

        // In the optimal case (no replacements were needed),
        // we are just returning the original String's reference,
        // without any new objects having been allocated.
        return s;
    }


/* LUE ADD */
    /**
     * Returns the current timestamp String in yyyyMMddHHmmss format
     *
     * @return the current timestamp value
     */
    public static String getCurrentTimestamp() {
        SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String strTimestamp = timestampFormat.format(new Date()); //current timestamp
        return strTimestamp;
    }
/*END LUE ADD */


public static String removeChar(String s, char c) {
	String r = "";
	for (int i = 0; i < s.length(); i ++) {
		if (s.charAt(i) != c) r += s.charAt(i);
	}
	return r;
}

public static String appendCharAt(String s, char c,int position,String type) {// type=+ or -
	String r = "";
	String strType = "+";
	System.out.println("*******************11"+r);

	if(type!=null){
		strType = type;
	}
	for (int i = 0; i < s.length(); i ++) {
	System.out.println("*******************12"+r);
		if(strType.equals("+")){
	System.out.println("*******************13"+r);
			if(i==position){
	System.out.println("*******************21"+r);
				r=r+c;
			}
			r += s.charAt(i);
		}else{
	System.out.println("*******************14"+r);
			if(i==s.length()-position){
	System.out.println("*******************15"+r);
				r=r+c;
			}
			r += s.charAt(i);
		}
	}
	return r;
}

/* LENDY ADD */

    /**
     *
     *
     *
     */
    public static String getVersion(String item, String stmtDate) {
		String version = "v1r00";

		try {

			System.out.println("");
			System.out.println("Get version for " + item + ", Statement Date : " + stmtDate);
			System.out.println("");

			com.checkfree.isolutions.property.Properties appCfg = com.checkfree.isolutions.property.PropertiesConfig.getApplicationSettings();

			if (appCfg!=null){
				if (appCfg.hasProperty(item+"_deploy_dates") && appCfg.hasProperty(item+"_versions")) {
					String dates = appCfg.getProperty(item+"_deploy_dates");
					String versions =  appCfg.getProperty(item+"_versions");

					System.out.println("Deploy Dates    : "+dates);
					System.out.println("Deploy Versions : "+versions);
					System.out.println("");

					StringTokenizer stDates = new StringTokenizer(dates,"|");
					StringTokenizer stVersions = new StringTokenizer(versions,"|");

					System.out.println("Date count    : "+stDates.countTokens());
					System.out.println("Version count : "+stVersions.countTokens());
					System.out.println("");

					if (stDates.countTokens() == stVersions.countTokens() && stDates.countTokens() > 0) {

						DateFormat df = new SimpleDateFormat(EbppxConstants.DATE_FORMAT);
						Date dtStmtDate = df.parse(stmtDate);

						String deployDate = stDates.nextToken();
						String deployVersion = stVersions.nextToken();
						Date dtDeployDate = df.parse(deployDate);

						if (stDates.hasMoreTokens()){

							while(stDates.hasMoreTokens()) {

								String nextDeployDate = "";
								String nextDeployVersion = "";

								if (stDates.hasMoreTokens()){
									nextDeployDate = stDates.nextToken();
									nextDeployVersion = stVersions.nextToken();
								} else {
									nextDeployDate = deployDate;
									nextDeployVersion = deployVersion;
								}

								Date dtNextDeployDate = df.parse(nextDeployDate);

								System.out.println("Statement Date   : "+stmtDate);
								System.out.println("Deploy Date      : "+deployDate+", Version : "+deployVersion);
								System.out.println("Next Deploy Date : "+nextDeployDate+", Version : "+nextDeployVersion);
								System.out.println("");

								if (dtStmtDate.equals(dtDeployDate)||dtStmtDate.before(dtNextDeployDate)){
									version = deployVersion;
									break;
								}

								deployDate = nextDeployDate;
								deployVersion = nextDeployVersion;
								dtDeployDate = dtNextDeployDate;

								version = nextDeployVersion;
							}

						} else {
							System.out.println("Statement Date   : "+stmtDate);
							System.out.println("Deploy Date      : "+deployDate+", Version : "+deployVersion);
							System.out.println("");
							if (dtStmtDate.after(dtDeployDate)||dtStmtDate.equals(dtDeployDate)){
								version = deployVersion;
							}
						}
					}
				}
			}
		}
		catch(Exception e) {
			System.out.println("Exception caught: " + e);
			System.out.println("");
			version = "v1r00";
		}
		finally {
			System.out.println("Version found : "+version);
			System.out.println("");

			version = "_" + version;
			return version;
		}
    }

    /**
     *
     *
     *
     */
    public static String getVersion(String item) {
		String version = "v1r00";

		try {

			System.out.println("");
			System.out.println("Get version for " + item);
			System.out.println("");

			com.checkfree.isolutions.property.Properties appCfg = com.checkfree.isolutions.property.PropertiesConfig.getApplicationSettings();

			if (appCfg!=null){

				if (appCfg.hasProperty(item+"_version")) {
					version = appCfg.getProperty(item+"_version");
				}
			}
		}
		catch(Exception e) {
			System.out.println("Exception caught: " + e);
			System.out.println("");
			version = "v1r00";
		}
		finally {
			System.out.println("Version found : "+version);
			System.out.println("");

			version = "_" + version;
			return version;
		}
    }

/*END LENDY ADD */

// Added by Meau to compute date differences

  /**
     * Compute the difference between two dates in years, months, and days.
     * The result is returned in a concatenated integer value of the form
     * ymmdd. So the difference between Apr 20, 2003 and Apr 15, 2025 would
     * be 211126 (21 years, 11 months, and 26 days) since 21 years and
     * 11 months gets you to May 20 2025, there are 31 days in May of 2025,
     * and it takes 25 days to go from May 20 2025 to April 15 2025! To split
     * the values off,
     * #years = return value / 10000,
     * #months = return value % 10000 / 100
     * #days = return value % 100.
     * This method will return a negative value if the 'from' value is after the
     * 'to' value (i.e. getDiff( from, to) = -getDiff( to, from )).
     *
     * @param pFrom The time to compute the difference from.
     * @param pTo Date The time to compute the difference to.
     *
     * @return int The differenct in the two dates in the form ymmdd.
     */
    public static long getDiff( String startDate, String endDate){

		int startDay = Integer.parseInt(startDate.substring(0,2));
		int startMonth = Integer.parseInt(startDate.substring(3,5));
		int startYear = Integer.parseInt(startDate.substring(6,10));

		int endDay = Integer.parseInt(endDate.substring(0,2));
		int endMonth = Integer.parseInt(endDate.substring(3,5));
		int endYear = Integer.parseInt(endDate.substring(6,10));

		// First convert the from and to Calender to long (milli seconds)
		// MAKE SURE THE Hour, Seconds and Milli seconds are set to 0, if you
		// already have you own Claender object otherwise the time will be
		// used in the comparision, later on.
		long from = new java.util.GregorianCalendar(startYear, startMonth, startDay).getTime().getTime();
		long to = new java.util.GregorianCalendar(endYear, endMonth, endDay).getTime().getTime();


		// Next subtract the from date from the to date (make sure the
		// result is a double, this is needed in case of Winter and Summer
		// Time (changing the clock one hour ahead or back) the result will
		// then be not exactly rounded on days. If you use long, this slighty
		// different result will be lost.
		double difference = to - from;


		// Next divide the difference by the number of milliseconds in a day
		// (1000 * 60 * 60 * 24). Next round the result, this is needed of the
		// Summer and Winter time. If the period is 5 days and the change from
		// Winter to Summer time is in the period the result will be
		// 5.041666666666667 instead of 5 because of the extra hour. The
		// same will happen from Winter to Summer time, the result will be
		// 4.958333333333333 instead of 5 because of the missing hour. The
		// round method will round both to 5 and everything is OKE....
		long days = Math.round((difference/(1000*60*60*24)));


		// Now we can print the day difference... Try it, it also works with
		// Feb 29...
		return(days);
	}

    public static int getMonthOfStmtDate(String stmtDate){
		String strStmtDate = stmtDate;
		strStmtDate = strStmtDate.substring(3,5);
		return Integer.parseInt(strStmtDate);

	}

	public static boolean isNumeric(String str){

		try{
			long number = Long.parseLong(str);
		}catch(NumberFormatException nex){
			return false ;
		}catch(NullPointerException nPex){
			return false ;
		}catch(Exception ex){
			return false ;
		}
		return true ;
	}

    public static String addMonthToDate(String stmtDate){
		int myDay = Integer.parseInt(stmtDate.substring(0,2));
		int myMonth = Integer.parseInt(stmtDate.substring(3,5));
		int myYear = Integer.parseInt(stmtDate.substring(6,10));

 		Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, myYear);
        c.set(Calendar.MONTH, myMonth);
        c.set(Calendar.DAY_OF_MONTH, myDay);
        c.add(Calendar.MONTH,0);

	    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        return formatter.format(c.getTime());
	}
    public static String substractMonthToDate(String stmtDate){
		int myDay = Integer.parseInt(stmtDate.substring(0,2));
		int myMonth = Integer.parseInt(stmtDate.substring(3,5));
		int myYear = Integer.parseInt(stmtDate.substring(6,10));

 		Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, myYear);
        c.set(Calendar.MONTH, myMonth);
        c.set(Calendar.DAY_OF_MONTH, myDay);
        c.add(Calendar.MONTH,-2);

	    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        return formatter.format(c.getTime());
	}

    private static String convertToHex(byte[] data) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                if ((0 <= halfbyte) && (halfbyte <= 9))
                    buf.append((char) ('0' + halfbyte));
                else
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        }
        return buf.toString();
    }

    public static String MD5(String text)
    throws NoSuchAlgorithmException, UnsupportedEncodingException  {
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        byte[] md5hash = new byte[32];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        md5hash = md.digest();
        return convertToHex(md5hash);
    }

    public static String SHA256(String text)
    throws NoSuchAlgorithmException, UnsupportedEncodingException  {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-256");
        byte[] md5hash = new byte[32];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        md5hash = md.digest();
        return convertToHex(md5hash);
    }

    public static String getHashSalt(String timestamp, String ipAddr){
        try {
			String hashSalt = "";
			String constant = "MaXIsHasH1ngSaLTkeY00";

			hashSalt = constant+timestamp.substring(2,4)+timestamp.substring(5,6)+timestamp.substring(7,8)+timestamp.substring(9,10)+timestamp.substring(11,12)+timestamp.substring(13,16)+ipAddr.substring(ipAddr.lastIndexOf(".")+1);
			System.out.println("****************:"+ipAddr.substring(ipAddr.lastIndexOf(".")+1));

            return hashSalt;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    // end added by Meau
}